<template>
    <div class="login-container">
      <div class="container">
           <div class="logo">
                <p class="logo-title"></p>
                <p class="line"></p>
                <div class="intro">
                    <p class="intro-title">千万家长的信赖首选</p>
                    <p>全国领先的教育云平台</p>
                    <p>千万家庭的放心选择</p>
                    <p>量身定制的个性化练习</p>
                </div>
           </div>
           <div class="login-form" v-if="educationLogin">
            <el-form autoComplete="on" :model="loginForm"  ref="loginForm" :rules="exuerules"
              label-position="left" label-width="0px" class="card-box">
                 <i class="icon" :class="{account: !loginByAccount}" @click="changeLogin"></i>
                  <i class="warn-infor" :class="{pc: !loginByAccount}"></i>
                  <div class="account" v-show="!loginByAccount">
                      <p class="login-title loginByAccountLoginTitle">用户登录</p>
                      <div class="inforBox">{{loginErrorInfor}}
                      </div>
                      <el-form-item prop="exueUsername" style="margin-bottom:30px;">
                          <el-input name="username" type="text" :maxlength="11" v-model="loginForm.exueUsername" autoComplete="on"
                                    placeholder="手机号/e学云ID号" @change="changeUserName">
                          </el-input>
                      </el-form-item>
                      <el-form-item prop="exuePassword">
                          <el-input name="password" type="password"  v-model="loginForm.exuePassword"
                                    autoComplete="on" placeholder="请输入密码" @keyup.enter.native="loginExue" @change="changePassword"></el-input>
                      </el-form-item>
                      <el-form-item class="form-mt">
                      <el-checkbox v-model="loginForm.exueRememberUname">记住用户名</el-checkbox>
                      <span class="rPass" @click="resetPassword">忘记密码</span>
                      <div class="login-btn">
                                <el-button type="primary" :loading="loading" @click.native.prevent="loginExue">
                                登录
                                </el-button>
                            </div>
                      <p class="goSchoolManage" @click="goSchoolManage">学校管理后台 ></p>
                    </el-form-item>
                  </div>
                  <div class="qrcode" v-show="loginByAccount">
                    <div class="login-title">扫码登录</div>
                    <div class="qr-img">
                        <qrcode :value="qr" size="180"></qrcode>
                        <div class="qr-wrong" v-if="timeout">
                            <img src="../../images/login/qr40.png">
                            <p>二维码已失效</p>
                            <a class="refresh" href="javascript:;" @click="refresh">请点击刷新</a>
                        </div>
                    </div>
                    <div class="tip">支持<span>教师及学生</span>账号</div>
                    <div class="tip">打开App，在 “我的” 界面使用扫一扫</div>
                    <p class="goSchoolManage" @click="goSchoolManage">学校管理后台 ></p>
                </div>
              </el-form>
           </div>
          <!-- 后台管理登录 -->
           <div class="login-form" v-if="schoolManageLogin">
            <el-form autoComplete="on" :model="manageLoginForm" ref="manageLoginForm" :rules="rules"
              label-position="left" label-width="0px" class="card-box">
                  <div class="account">
                      <p class="login-title loginByAccountLoginTitle">后台管理登录</p>
                       <div class="inforBox">{{loginErrorInfor}}
                       </div>
                        <el-form-item style="margin-bottom:30px;" prop="username">
                          <el-input name="username" type="text" v-model="manageLoginForm.username" autoComplete="on" @change="changeUserName"
                                    placeholder="手机号/e学云ID号" :maxlength="11"></el-input>
                        </el-form-item>
                      <el-form-item prop="password">
                          <el-input name="password" type="password" @keyup.enter.native="handleLogin" v-model="manageLoginForm.password" @change="changePassword"
                                    autoComplete="on" placeholder="请输入密码"></el-input>
                      </el-form-item>
                      <el-form-item class="form-mt">
                            <el-checkbox v-model="manageLoginForm.rememberUname">记住用户名</el-checkbox>
                            <span class="rPass" @click="resetPassword">忘记密码</span>
                            <div class="login-btn">
                                <el-button type="primary" :loading="loading"
                                 @click.native.prevent="handleLogin">
                                登录
                                </el-button>
                            </div>
                            <!-- <div class="login-btn">
                                <el-input name="thirdUserAccount" type="text" v-model="thirdUserAccount" @change="changePassword"
                                    autoComplete="on" placeholder="请输入身份证号"></el-input>
                            </div>
                            <div class="login-btn">
                                <el-button type="primary"
                                 @click.native.prevent="handleLogin1">
                                第三方模拟登录
                                </el-button>
                            </div> -->
                            
                            <p class="goSchoolManage" @click="goEducationLogin">e学云教育平台 ></p>
                    </el-form-item>
                  </div>
              </el-form>
           </div>
      </div>
           <p class="footer">
               Copyright ©2012-{{currentYear}} juziwl, All Rights Reserved  苏州橘子网络科技股份有限公司运营    工信部备案号
                <!-- 苏ICP备14004226号-20 -->
                <!-- http://www.miibeian.gov.cn/state/outPortal/loginPortal.action 这个地址有问题 打开400-->
                <a href="http://www.miibeian.gov.cn" target="_blank">苏ICP备14004226号-20</a>
                <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=32050802010643">
                    <img src="../../images/login/tubiao.png"/>
                    <span>苏公网安备 32050802010643号</span>
                 </a>
           </p>
    </div>
		 	
</template>
<script>
import { mapGetters } from 'vuex';
// import NProgress from 'nprogress';
import qrcode from 'qrcode.vue';
import uuid from 'uuid/v1';
import moment from 'moment';
import {scanCodeLogin} from 'api/login';
import { managerWeb } from 'api/platform';
import { buriedPoint } from 'api/identifychange';
export default {
    components: {qrcode},
    name: 'login',
    data() {
        return {
            currentYear: moment(new Date()).format('YYYY'),
            loginErrorInfor: '', // 登录失败的提示
            educationLogin: true,
            loginStatus: '1', // 默认展示的前台的登录框
            qr: null,
            key: uuid(),
            timer: null,
            timeout: false,
            loginByAccount: true,
            loginForm: {// exue前台的登录页面
                exueUsername: '',
                exuePassword: '',
                exueRememberUname: false// 是否记住用户名
            },
            loading: false,
            showDialog: false,
            // 后台管理登录
            schoolManageLogin: false,
            manageLoginForm: {// 后台管理登录
                username: '',
                password: '',
                rememberUname: false// 是否记住用户名
            },
            rules: {
                username: [
                    { required: true, trigger: 'blur', message: '请输入手机号/e学云ID号' }
                ],
                password: [
                    { required: true, trigger: 'blur', message: '请输入密码' },
                     { min: 6, max: 16, message: '密码长度为6到16个字符', trigger: 'blur' },
                   { pattern: /^[A-Za-z0-9]*$/, message: '您的密码错误', trigger: 'blur'}// 数字和字母组合
                ]
            },
            exuerules: {
                exueUsername: [
                    { required: true, trigger: 'blur', message: '请输入手机号/e学云ID号' }
                ],
                exuePassword: [
                    { required: true, trigger: 'blur', message: '请输入密码' },
                     { min: 6, max: 16, message: '密码长度为6到16个字符', trigger: 'blur' },
                   { pattern: /^[A-Za-z0-9]*$/, message: '您的密码错误', trigger: 'blur'}// 数字和字母组合
                ]
            },
            thirdUserAccount: '' // 第三方登陆的身份证号
        };
    },
    computed: {
        // ...mapGetters(['authType', 'avatar', 'username', 'schoolId'])
        ...mapGetters(['token', 'authType', 'avatar', 'username', 'schoolId', 'exueUsername'])
    },
    created() {
        this.qr = JSON.stringify({
            type: 3,
            content: {
                key: this.key
            }
        });
        this.manageLoginForm.username = this.username?this.username:'';
        this.manageLoginForm.rememberUname = this.username?true:false;
        this.loginForm.exueUsername = this.exueUsername?this.exueUsername:'';
        this.loginForm.exueRememberUname = this.exueUsername?true:false;
        this.switchLogin()
    },
    mounted() {
        var formattedParams = {};
        const params = window.location.href.indexOf('?') > -1 && window.location.href.split('?')[1].split('&');
        for (let i = 0; i < params.length; i++) {
            formattedParams[params[i].split('=')[0]] = params[i].split('=')[1];
        }
        console.log(formattedParams, '------formattedParams')
        if (!formattedParams.accessToken) return;

        this._checkThirdLogin(formattedParams.accessToken);
    },
    methods: {
        changeUserName() {
            this.loginErrorInfor=null;// // 登录失败的提示
        },
        changePassword() {
            this.loginErrorInfor=null;// // 登录失败的提示
        },
        changeLogin() {
            this.loginByAccount = !this.loginByAccount;
            this.switchLogin();
        },
        switchLogin() { // 账号登录和二维码登录切换
            this.loading = false;
            if (!this.loginByAccount) { // 账号登录
                if (this.timer) {
                    clearTimeout(this.timer);
                    this.timer = null;
                }
            } else { // 二维码登录
                this.refresh();
            }
        },
        refresh() {
            this.timeout = false;
            this.startScan();
        },
        startScan() { // 开始扫描，设置超时
            this.scanLogin();
            this.timer = setTimeout(() => {
                this.timer = null;
                this.showTimeout();
            }, 60000);
        },
        scanLogin() { // 递归扫描状态
            scanCodeLogin(this.key).then(data => {
                this.recordingBuriedPoint(data.data.content.userType, data.data.content.userId, data.data.content.schoolId, data.data.content.token)
                if (this.timer) {// 扫码成功之后 清定时器
                    clearTimeout(this.timer);
                    this.timer = null;
                }
                window.location.href = process.env.FRONT_END_URL + data.data.content.token;
            }).catch(e => {
                if (this.loginByAccount && !this.timeout && this.timer) { // 二维码登录状态 不超时
                    setTimeout(() => {
                        this.scanLogin();
                    }, 1000);
                }
            });
        },
        showTimeout() {
            this.timeout = true;// 刷新提示的遮罩
        },
        loginExue() {
            this.exueLogin();
        },
        // e学前台登录
        exueLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$store
                    .dispatch('exueLoginByUsername', this.loginForm)
                    .then((res) => {
                        this.loading = false;
                        this.loginErrorInfor='';// // 登录失败的提示
                        this.recordingBuriedPoint(res.userType, res.userId, res.schoolId, res.token);// 埋点
                        window.location.href = process.env.FRONT_END_URL + res.token;
                        
                    })
                    .catch(e => {
                        this.loading = false;
                        if (e.length > 100) { 
                            e ='';
                        }
                        this.loginErrorInfor=e; // 登录失败的提示
                    });
                } else {
                    return false;
                }
            });
        },
         // 登陆时---前台 --> 教师端和学生端埋点
        recordingBuriedPoint(userType, userId, schoolId, AccessToken) {
            let saveData= {
                AccessToken,
                event: 'WebLogin',
                scene: 'WebLogin',
                'ly_userType': userType,
                'ly_userId': userId,
                'ly_schoolId': schoolId,
                'ly_os': 'web',
                'ly_dateTime': moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            };
            buriedPoint(saveData)
        },
        
        // 学校后台管理登录
        handleLogin() {
            this.$refs.manageLoginForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    this.$store
                    .dispatch('LoginByUsername', this.manageLoginForm)
                    .then((res) => {
                        this.loading = false;
                        this.loginErrorInfor='';
                        this.$router.push({ path: '/' });
                        this.$store.dispatch('GetInfo').then(e => {
                            this.loginErrorInfor=''; // 登录失败的提示

                        }).catch(e => {
                            this.loginErrorInfor=e;// 登录失败的提示
                            this.loading = false;
                            NProgress.done(); // 结束Progress
                        })
                    })
                    .catch(e => {
                        this.loading = false;
                        if (e.length > 100) { 
                            e ='';
                        }
                        this.loginErrorInfor=e; // 登录失败的提示
                    });
                } else {
                    return false;
                }
            });
        },
        handleLogin1() {
            if (!this.thirdUserAccount) return;
            managerWeb(this.thirdUserAccount).then(res => {
                console.log(res, 'res login')
            })
        },
        // Token 第三方登陆
        _checkThirdLogin(token) {
            this.$store
            .dispatch('exueLoginByToken', token)
            .then((res) => {
                this.loginErrorInfor='';
                this.$router.push({ path: '/' });
                this.$store.dispatch('GetInfo').then(e => {
                    this.loginErrorInfor=''; // 登录失败的提示
                }).catch(e => {
                    this.loginErrorInfor=e;// 登录失败的提示
                    NProgress.done(); // 结束Progress
                })
            })
            .catch(e => {
                this.loading = false;
                if (e.length > 100) { 
                    e ='';
                }
                this.loginErrorInfor=e; // 登录失败的提示
            });
        },
        // 重置密码 发字段 判断是前台的还是后台的忘记密码
        resetPassword() {
            this.$router.push({path: '/reset', query: {loginStatus: this.loginStatus}});
        },
        goSchoolManage() {// 切换到后台
            this.loginByAccount =false;
            this.loading = false;
            this.loginErrorInfor='';// // 登录失败的提示
            this.$refs.loginForm.resetFields();
            this.schoolManageLogin=true;
            this.educationLogin=false;
            this.loginStatus='2';
        },
        goEducationLogin() {// 切换到前台
            this.loginByAccount = true;
            this.refresh();
            this.loading = false;
            this.loginErrorInfor='';// // 登录失败的提示
            this.$refs.manageLoginForm.resetFields();
            this.schoolManageLogin=false;
            this.educationLogin=true;
            this.loginStatus='1';
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped> 
@import "src/styles/var.scss";
@import "src/styles/mixin.scss";
// 大于1200px
@media screen and (min-width: 1200px) {
    .container{
         width:1120px;
    }
}
// 小于等于1200
@media screen and (max-width: 1200px) {
    .container{
         width:920px;
    }
}
.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 5px;
}
.container{
    
    position: relative;
    max-width:1120px;
    min-width: 920px;
    margin:0 auto;
    height: 100%;
     .logo{
        padding-top:150px;
        width:400px;
        .logo-title{
            font-size: 46px;
            height: 60px;
            width: 402px;
            background: url(../../images/login/logo.png) left no-repeat;
            position: relative;
        }
        .line{
            height: 1px;
            background: url(../../images/login/line.png) left no-repeat;
            margin:36px 0;
        }
        .intro{
            p{
                font-size: 17px;
                color:#333;
                height: 36px;
                line-height: 46px;
            }
            .intro-title{
                font-size: 32px;
                color:#333;
                line-height: 36px;
                font-weight: 500;
                height: 36px;
                margin-bottom: 10px;
            }
        }
    }
}

.goSchoolManage{
    color: #999;
    font-size:13px;
    cursor: pointer;
    text-align: right;
    margin-top: 2px;
    display: block;
    float:right;
}
.login-container {
  @include relative;
  height: 100vh;
  min-height: 800px;
  background: url(../../images/login/bg.jpg) no-repeat 100% 100%;
  background-size:cover;

  input:-webkit-autofill {
    // -webkit-box-shadow: 0 0 0px 1000px #fff inset !important;
    -webkit-text-fill-color: #333 !important;
  }
  input {
    background: transparent;
    -webkit-appearance: none;
    border-radius: 0px;
    height: 44px;
    border:1px solid #ccc; // 登陆样式修改
    box-shadow:none; // 去除边框投影
    -webkit-box-shadow:none;
    &:focus{
      border:1px solid $primary; // 添加选中边框样式
    }
  }
  .el-input {
    display: inline-block;
    width: 100%;
    margin-top: 6px;
  }
  .login-form {
    position: absolute;
    right:0px;
    top:50%;
    transform: translateY(-50%);
    width: 400px;
    height: 434px;
    padding: 30px 25px;
    border: solid 1px rgba(238, 238, 238, 1);
    background: #fff;
    box-sizing: border-box;
    .login-title{
        height: 46px;
        line-height: 46px;
        font-size:22px;
        color:#333;
        margin-bottom: 20px;
    }
    .inforBox{
        display: inline-block;
        margin-bottom: 20px;
        color: #ff5e2c;
        font-size: 14px;
        height: 18px;
        line-height: 18px;
        width:348px;
        margin-bottom: 28px;
        overflow: hidden;/*超出部分隐藏*/
        white-space: nowrap;/*不换行*/
        text-overflow:ellipsis;/*超出部分文字以...显示*/
    }
    .infor{
        display:inline-block;
        color:#ff5e2c;
        font-size:16px;
        height: 16px;
      
    }
    .loginByAccountLoginTitle{
         margin-bottom: 0px;
    }
    i.icon {
        position: absolute;
        top: 1px;
        right: 1px;
        width: 80px;
        height: 80px;
        background: url(../../images/login/pc.png) no-repeat;
        cursor: pointer;
        &.account {
             background: url(../../images/login/qrcode.png) no-repeat;
        }
    }
    i.warn-infor{
        position: absolute;
        background: url(../../images/login/mima.png) no-repeat;
        top: 23px;
        right: 82px;
        width: 80px;
        height:28px;
        &.pc{
            background: url(../../images/login/qr.png) no-repeat;
        }
    }
    .account {
      .login-btn {
        text-align: center;
        margin-top:10px;
        button{
        margin-top:22px;
          height: 46px;
          font-size:20px;
        }
      }
      .rPass {
        float: right;
        cursor: pointer;
        height: 30px;
        line-height: 30px;
      }
    }
     .qrcode {
        color: #fff;
        .title {
            font-size: 18px;
            padding: 20px;
        }
        .qr-img {
            position: relative;
            width: 180px;
            height: 180px;
            margin: 0 auto;
            overflow: hidden;
            margin-top:40px;
            .qr-wrong {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                text-align: center;
                img {
                     width: 200px;
                     height: 200px;
                }
                p {
                    position: absolute;
                    top: 40px;
                    color: #000;
                    width: 100%;
                }
                .refresh {
                    position: absolute;
                    bottom: 28px;
                    left: 40px;
                    color: #fff;
                    font-size: 14px;
                    width: 104px;
                    height: 34px;
                    line-height: 34px;
                    display: block;
                    background: #f40;
                    text-decoration: none;
                   
                }
            }
        }
        .tip {
            font-size: 16px;
            color:#333;
            text-align: center;
            span{
                display: inline-block;
                color:#f40;
            }
           margin-top: 16px;
           margin-bottom: 12px;
        }
    }
  }
  .el-form-item {
    color: #454545;
    margin-bottom:0px;
    .el-form-item__error {
      margin-top: 8px;
    }
    .el-button {
      width: 100%;
    }
  }
  .form-mt {
      margin-top: 20px;
  }
  .el-form-item:nth-child(1){
      margin-bottom:0px;
  }
  .el-tabs {
    width: 100%;
    .el-tabs__header {
      border: none;
    }
    .el-tabs__content {
      > .el-form-item {
        border: none;
      }
    }
  }
  .el-tabs__nav {
    display: flex;
    width: 100%;
    background: #ddd;
    .el-tabs__active-bar {
      height: 100%;
      background: #fff;
    }
    .el-tabs__item {
      flex: 1;
      font-size: 18px;
      height: 48px;
      line-height: 48px;
      z-index: 99;
      text-align: center;
      &.is-active {
        color: $primary;
      }
    }
  }
}
.footer{
    text-align: center;
    position: absolute;
    bottom:60px;
    height: 36px;
    line-height: 36px;
	font-family: MicrosoftYaHei;
	font-size: 14px;
	font-weight: normal;
	font-stretch: normal;
	line-height: 46px;
	letter-spacing: 0px;
	color: #777777;
    width:100%;
}
</style>
